package cn.agiledata.bank.login.action;

import java.awt.Image;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ocx.AESWithJCE;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.account.service.IAccountConst;
import cn.agiledata.bank.account.service.IAccountService;
import cn.agiledata.bank.account.service.IReturnCodeHolder;
import cn.agiledata.bank.common.action.BaseMainAction;
import cn.agiledata.bank.common.dao.AccountTemplate;
import cn.agiledata.bank.common.exception.BusinessException;
import cn.agiledata.bank.common.service.SysSet;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.ConvertUtil;
import cn.agiledata.bank.common.util.SecurityUtil;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.UniqueIdentityUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.common.util.WebUtil;
import cn.agiledata.bank.facade.ServiceFacade;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.login.form.EmailForm;
import cn.agiledata.bank.login.form.LoginForm;
import cn.agiledata.bank.login.form.RegisterForm;
import cn.agiledata.bank.login.form.ResetPwdForm;
import cn.agiledata.bank.myspace.exception.MySpaceException;
import cn.agiledata.bank.netReturn.logic.NetReturnResponse;

import com.vnv.infrastructure.exception.IPBAppException;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class MainAction extends BaseMainAction implements Constant {

	public int hasAccessPermission(int accessLevel, HttpServletRequest request)
			throws IPBException {
		int result = 1;
		return result;
	}

	protected ActionForward getAppExceptionForward(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, IPBAppException e) {
		// TODO Auto-generated method stub
		ActionForward forward = mapping.findForward("failure");
		if (forward == null) {
			return super.getAppExceptionForward(mapping, actionForm, request,
					response, e);
		} else {
			if (e instanceof MySpaceException) {
				request.setAttribute("bundle", "MySpace");
			}
			return forward;
		}
	}

	/**
	 * 检验验证码
	 * 
	 * @param request
	 * @param form
	 * @throws BusinessException
	 */
	public void checkVericode(HttpServletRequest request, String vericode)
			throws BusinessException {

		String refer = (String) WebUtil
				.getSessionString(request, SESS_VERICODE);

		if (refer == null) {
			throw BusinessException.VERIFYCODE_INVALID;
		}
		// 校验码取出一次后就立即更新
		this.refreshVericode(request);

		if (refer == null || !refer.equals(vericode)) {
			// 校验码不正确
			throw BusinessException.WRONG_VERIFYCODE;
		}
	}

	/**
	 * 重新得到验证码
	 * 
	 * @param request
	 */
	private void refreshVericode(HttpServletRequest request) {
		String vericode = genVericode();
		WebUtil.setSessionString(request, SESS_VERICODE, vericode);
	}

	/** 按表单存放校验码 */
	public String genVericode() {
		String code = UniqueIdentityUtil.createRandomString(4);
		return code;
	}

	/**
	 * Method execute
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward logon(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm theForm = (LoginForm) form;
		AccountSummary accountSummary = null;

		HttpSession session = request.getSession();
		String mcrypt_key_1 = (String) session.getAttribute("mcrypt_key");// 获取session中随机因子
		session.removeAttribute("mcrypt_key");// 清除session

		String atype = theForm.getLogon_atype();
		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");
		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		//验证码
		if (setService.getCheckVericode()) {
			String corp_sys_vericode = theForm.getLogon_corp_sys_vericode();
			String person_sys_vericode = theForm.getLogon_person_sys_vericode();
			String vericode = StringUtil.isStrEmpty(person_sys_vericode) ? corp_sys_vericode
					: person_sys_vericode;
			this.checkVericode(request, vericode);
		}
		//验证码end
		if (ACCOUNT_TYPE_BUYER.equals(atype)) { // 个人客户
			String username = theForm.getLogon_person_email().trim(); // email
			String password1 = theForm.getLogon_person_passPerson(); // 密码
			String password = AESWithJCE.getResult(mcrypt_key_1, password1);
			password = SecurityUtil.encryptoMD5String(password);
			Map map = new HashMap();
			map.put("username", username);
			map.put("password", password);
			map.put("ip", request.getRemoteAddr());
			request.setAttribute("userinfo", map);
			// 黑名单用户禁止登录
			if (service.checkBlackList(username)) {
				AccountTemplate accountTemplate = (AccountTemplate) IPBAppFactory.getObj("accountTemplate");
				// 发送邮件通知
	        	accountTemplate.sendMail("0", "黑名单用户登录", username);
	        	
	        	Account account = service.findAccountByEmail(username);
	        	// 记录异常日志
	        	accountTemplate.saveLog(account, "0", "黑名单用户登录");
				throw BusinessException.BLACKLIST_LOGIN;
			}
			accountSummary = service.userLogon(WEB, map);
			request.getSession().setAttribute("userinfo", accountSummary);
		} else if (ACCOUNT_TYPE_CORPORATION.equals(atype)) {
			String username = theForm.getLogon_corp_email().trim(); // email
			String password1 = theForm.getLogon_corp_passCorp(); // 密码
			String password = AESWithJCE.getResult(mcrypt_key_1, password1);// 调用解密接口
			password = SecurityUtil.encryptoMD5String(password);
			String operatorId = theForm.getLogon_corp_operator().trim(); // 操作员
			
			Map map = new HashMap();
			map.put("username", username);
			map.put("password", password);
			map.put("operatorId", operatorId);
			map.put("ip", request.getRemoteAddr());
			request.setAttribute("userinfo", map);
			// 黑名单用户禁止登录
			if (service.checkBlackList(username)) {
				AccountTemplate accountTemplate = (AccountTemplate) IPBAppFactory.getObj("accountTemplate");
				// 发送邮件通知
	        	accountTemplate.sendMail("0", "黑名单商户登录", username);
	        	
	        	Account account = service.findAccountByEmail(username);
	        	// 记录异常日志
	        	accountTemplate.saveLog(account, "0", "黑名单商户登录");
				throw BusinessException.BLACKLIST_LOGIN;
			}
			accountSummary = service.userLogon(WEB, map);
			request.getSession().setAttribute("userinfo", accountSummary);
		} else {
			throw new BusinessException(IReturnCodeHolder.LOGON_FORM_INFORMAL);
		}

		if (accountSummary == null) {
			throw BusinessException.INFRA_FAILURE;
		}
		ServletContext sc=this.getServlet().getServletContext();
		accountSummary.setRoot(WebUtil.getRoot(request)); // 设置应用程序访问地址根

		WebUtil.setSessionString(request, Constant.SESSION_ACCOUNT_SUMMARY,
				accountSummary);
		// add by zxj
		// 写进用户此次登录的sessionId
		if (ACCOUNT_TYPE_BUYER.equals(atype)) {
			WebUtil.setApplicationMap(sc,
					accountSummary.getAccount().getId(), request
							.getRequestedSessionId(), APPLICATION_SESSION_ID);
		} else {
			WebUtil.setApplicationMap(this.getServlet().getServletContext(),
					accountSummary.getOperatorCode(), request
							.getRequestedSessionId(), APPLICATION_SESSION_ID);
		}

		// zln 修正 2008-01-12
		// 增加抽奖页面登陆时跳转控制
		if (request.getParameter("lottery") != null) {
			// 跳转到抽奖页面
			return mapping.findForward("lottery");
		}
		if (request.getParameter("integral") != null) {
			// 跳转到抽奖页面
			return mapping.findForward("integral");
		}
		if (session.getAttribute("thesign") != null) {
			// 跳转到手机充值页面
			session.removeAttribute("thesign");
			AccountTemplate at = (AccountTemplate) IPBAppFactory
			.getObj("accountTemplate");
			SubAccount sa=(SubAccount)accountSummary.getSubAccountList().get(0);
			if ("true".equals(at.authentication(sa.getId().toString())))//未进行实名认证
				session.setAttribute("message","recharge.noauth");
			else
				return mapping.findForward("gatewaytest");
		}
		String modual = WebUtil.getSessionString(request, "modual");
		if (modual == null) {
			modual = "space";
		}
		String requestURL = (String) request.getSession().getAttribute(
				"requestURL");
		String url = request.getContextPath() + "/route.do?modual=" + modual;
		if (StringUtils.isNotBlank(requestURL)) {
			url = requestURL;
			request.getSession().removeAttribute("requestURL");
		}
		// response.sendRedirect(url);
		// 此处url同帐户类型以及是否操作员有关
		// 走退款接口时,登录直接跳转到指定的url
		NetReturnResponse netReturn = (NetReturnResponse) request.getSession()
				.getAttribute("netReturnResponse");
		if (netReturn != null
				&& COMPANY_TYPE_SIMPLE.equals(accountSummary.getCompanyType())
				&& IAccountConst.USERTYPE_CORP_OPERATOR.equals(accountSummary
						.getUserType())) {
			url = request.getContextPath()
					+ "/route.do?modual=manage$waitingPay";
			request.getSession().setAttribute("batchModel",
					netReturn.getBatchModel());
		}
		session.setAttribute("message","bank.information");
		session.setAttribute("question2",accountSummary.getAccount().getQuestion());
		response.sendRedirect(url);

		return mapping.findForward(Constant.FORWORD_NULL);
	}

	/**
	 * Method execute
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward register(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		RegisterForm theForm = (RegisterForm) form;
		if (setService.getCheckVericode()) {
			String vericode = theForm.getRegister_sys_vericode();
			this.checkVericode(request, vericode);
		}

		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");

		if ("Y".equalsIgnoreCase(theForm.getRegister_useMobile())) {
			// 手机验证
			this.mobileConfirm(request, theForm);
		}

		HttpSession session = request.getSession();
		String mcrypt_key_1 = (String) session.getAttribute("mcrypt_key");// 获取session中随机因子
		session.removeAttribute("mcrypt_key");// 清除session

		String type = theForm.getRegister_atype(); // 设置客户类型
		request.getSession().setAttribute("type", type);
		String email1 = "N".equals(theForm.getRegister_useEmail()) ? null
				: theForm.getRegister_email();
		String email = (email1 == null ? null : email1.trim());

		String password1 = theForm.getRegister_loginPass();
		String loginPass = AESWithJCE.getResult(mcrypt_key_1, password1);

		String password2 = theForm.getRegister_payPass();
		String payPass = AESWithJCE.getResult(mcrypt_key_1, password2);

		String corpName = theForm.getRegister_corpName();
		String corpTel = theForm.getRegister_corpTel();
		String corpLicenceNo = theForm.getRegister_corpLicenceNo();
		String question = theForm.getRegister_question().replaceAll(" ", "");
		String answer = theForm.getRegister_answer().replaceAll(" ", "");
		// 法人姓名
		String prinName = theForm.getRegister_prinName();
		// 法人代表身份证号
		String corpBossId = theForm.getRegister_corpBossId();
		// 注册资金
		Double capitalAmount = theForm.getRegister_capitalAmount();
		String submitMethod = theForm.getSubmitMethod(); // 提交方式 身份证还是传真
		FormFile idcardPhoto = theForm.getIdcardPhoto(); // 正面图片
		FormFile backOfIdcardPhoto = theForm.getBackOfIdcardPhoto();// 背面图片
		FormFile cardPhoto=theForm.getCardPhoto();
		// String corpFinanceId = theForm.getRegister_corpFinanceId();
		String corpZip = theForm.getRegister_corpZip();
		String corpAddr = theForm.getRegister_corpAddr();
		String corpFinanceName = theForm.getRegister_corpFinanceName();
		String corpAccountLicenceNo = theForm
				.getRegister_corpAccountLicenceNo();
		String corpOrganizeNo = theForm.getRegister_corpOrganizeNo();
		String corpTaxId = theForm.getRegister_corpTaxId();
		InputStream idcardPhotoStream = null;
		InputStream idcardPhotoBackStream = null;
		InputStream cardPhotoStream=null;
		
		String intr_email1 = theForm.getIntroduce_email();
		String intr_email = "";
		if (intr_email1 != null && !intr_email1.equals("")) {
			intr_email = intr_email1.trim();
		}

		String mobile = (String) theForm.getRegister_mobile();
		mobile = "N".equals(theForm.getRegister_useMobile()) ? null : mobile;
		String project = theForm.getRegister_project();
		WebUtil.removeSessionAttribute(request, SESS_SMS_MOBILE);
		WebUtil.removeSessionAttribute(request, SESS_SMS_VERICODE);
		if (Constant.ACCOUNT_TYPE_CORPORATION.equals(type)) {
			if(cardPhoto == null || cardPhoto.getFileSize() == 0)
			{
				//营业执照图片不能为空
				throw BusinessException.CARD_PHOTO_EMPTY;
			}else if(cardPhoto.getFileSize() > Constant.FILESIZE_512K){
				//营业执照图片数据大小超出范围
				throw BusinessException.CARD_PHOTO_OVER_512KB;
			}else
			{
				cardPhotoStream = cardPhoto.getInputStream();
				Image image = ImageIO.read(cardPhotoStream);
				cardPhotoStream.close();
				if (image == null) {
					throw BusinessException.CARD_PHOTO_FORMACT_ERROR;
				}
			}
			if (!StringUtil.isIdcardNo(corpBossId)) {// 身份证号码格式错误
				throw BusinessException.IDCARD_FORMACT_ERROR;
			} else if (Constant.AUTHENTICATION_METHOD_IDCARD_UPLOAD
					.equals(submitMethod)) {// 上传身份证扫描图片
				if (idcardPhoto == null || idcardPhoto.getFileSize() == 0) {// 身份证正面图片为空
					throw BusinessException.IDCARD_PHOTO_EMPTY;
				} else if (idcardPhoto.getFileSize() > Constant.FILESIZE_512K) {// 身份证正面图片数据太大
					throw BusinessException.IDCARD_PHOTO_OVER_512KB;
				} else {// 身份证正面图片不为空且数据大小没有超出范围
					idcardPhotoStream = idcardPhoto.getInputStream();
					Image image = ImageIO.read(idcardPhotoStream);
					idcardPhotoStream.close();
					if (image == null) {
						throw BusinessException.IDCARD_PHOTO_FORMACT_ERROR;
					}

					if (backOfIdcardPhoto == null
							|| backOfIdcardPhoto.getFileSize() == 0) {// 身份证背面图片为空
						// 保存一代身份证图片
						idcardPhotoStream = idcardPhoto.getInputStream();
					} else {// 身份证背面图片不为空
						if (backOfIdcardPhoto.getFileSize() > Constant.FILESIZE_512K) {// 身份证背面图片数据太大
							throw BusinessException.IDCARD_PHOTO_BACK_OVER_512KB;
						} else {
							idcardPhotoBackStream = backOfIdcardPhoto
									.getInputStream();
							Image imageBack = ImageIO
									.read(idcardPhotoBackStream);
							idcardPhotoBackStream.close();
							if (imageBack == null) {
								throw BusinessException.IDCARD_PHOTO_FORMACT_ERROR;
							}

							// 保存二代身份证
							idcardPhotoStream = idcardPhoto.getInputStream();
							idcardPhotoBackStream = backOfIdcardPhoto
									.getInputStream();
						}
					}
				}
			}
		}
		Map map = new HashMap();
		map.put("email", email);
		map.put("mobile", mobile);
		map.put("type", type);
		map.put("corpName", corpName);
		map.put("corpTel", corpTel);
		map.put("corpLicenceNo", corpLicenceNo);
		map.put("corpZip", corpZip);
		map.put("corpAddr", corpAddr);
		map.put("corpFinanceName", corpFinanceName);
		map.put("question", question);
		map.put("answer", answer);
		map.put("corpBossId", corpBossId);
		map.put("capitalAmount", capitalAmount);
		map.put("prinName", prinName);
		map.put("cardphoto", cardPhotoStream);
		map.put("idcardPhoto", idcardPhotoStream);
		map.put("backOfIdcardPhoto", idcardPhotoBackStream);
		// map.put("corpFinanceId", corpFinanceId);
		map.put("corpAccountLicenceNo", corpAccountLicenceNo);
		map.put("corpOrganizeNo", corpOrganizeNo);
		map.put("corpTaxId", corpTaxId);
		map.put("loginPassword", loginPass);
		map.put("payPassword", payPass);
		map.put("intremail", intr_email);
		map.put("url", ConvertUtil.getRequestURL(request));
		service.userRegister(WEB, project, map);
		if ("Y".equals(theForm.getRegister_useEmail())) { // 如果是用email注册，设置成功参数
			request.setAttribute("email", email);
			request.setAttribute(MESSAGE, REGISTER_EMAIL_SUCCESS);
		} else { // 如果是手机注册，设置成功参数
			request.setAttribute(MESSAGE, REGISTER_MOBILE_SUCCESS);
		}
		if (type.equals(Constant.ACCOUNT_TYPE_BUYER)) {
			return mapping.findForward(SUCCESS);
		} else {
			return mapping.findForward("companySuccess");
		}
	}

	/**
	 * 新的手机验证
	 * 
	 * @param form
	 * @return
	 * @throws BusinessException
	 */
	public String mobileConfirm(HttpServletRequest request, RegisterForm form)
			throws BusinessException {
		String vericode = form.getRegister_vericode();
		if (vericode == null) {
			throw BusinessException.INFORMAL_FORM;
		}
		String snap = (String) WebUtil.getSessionString(request,
				SESS_SMS_VERICODE);
		if (snap == null) {
			throw BusinessException.NOT_SMS_SUBMIT;
		}
		String[] tuple = snap.split("#");

		if (!vericode.equals(tuple[0])) {
			throw BusinessException.WRONG_SMS_CONFIRM;
		}

		String mobile = tuple[1];
		WebUtil.setSessionString(request, SESS_SMS_MOBILE, mobile);
		return mobile;
	}

	/**
	 * 忘记密码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward forgot(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");
		EmailForm theForm = (EmailForm) form;
		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		if (setService.getCheckVericode()) {
			String vericode = theForm.getSys_sys_vericode();
			this.checkVericode(request, vericode);
		}
		String email = theForm.getSys_email();
		service.sendPasswordMail(email);
		request.setAttribute(MESSAGE, FORGOT_SUCCESS);
		return mapping.findForward(SUCCESS);
	}

	/**
	 * 个人或企业admin通过email申请重置登录密码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward applyResetLoginPasswordByEmail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String email = resetForm.getEmail();
		String regEx="^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
		Pattern pat = Pattern.compile(regEx);  
		Matcher mat = pat.matcher(email);  
		boolean rs = mat.find();  
		if (!rs) {
			return mapping.findForward("failure");
		}
		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		if (setService.getCheckVericode()) {
			String vericode = resetForm.getVericode();
			this.checkVericode(request, vericode);
		}

		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");

		// 修改account，设置resetPwdCode，并发送email，告知用户重置登录密码的确认码
		service.sendResetPasswordCodeMail(email,
				IAccountConst.RESET_PWD_TYPE_LOGIN);

		return mapping.findForward("success");
	}

	/**
	 * 个人通过mobile申请重置登录密码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward applyResetLoginPasswordByMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String mobile = resetForm.getMobile();

		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		if (setService.getCheckVericode()) {
			String vericode = resetForm.getVericode();
			this.checkVericode(request, vericode);
		}

		ServiceFacade sf = (ServiceFacade) IPBAppFactory
				.getObj("serviceFacade");

		// 修改account，设置resetPwdCode，并发送短信，告知用户重置登录密码的确认码
		sf.sendResetPasswordCodeSms(mobile, IAccountConst.RESET_PWD_TYPE_LOGIN);

		return mapping.findForward("success");
	}

	/**
	 * 个人或企业admin通过email重置登录密码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward resetLoginPasswordByEmail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String email = resetForm.getEmail();
		HttpSession session = request.getSession();
		String mcrypt_key_1 = (String) session.getAttribute("mcrypt_key");// 获取session中随机因子
		session.removeAttribute("mcrypt_key");// 清除session
		String password1 = resetForm.getNewPass();
		String loginPass = AESWithJCE.getResult(mcrypt_key_1, password1);
		
		
		String regEx="^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
		Pattern pat = Pattern.compile(regEx);  
		Matcher mat = pat.matcher(email);  
		boolean rs = mat.find();  
		if (!rs) {
			throw BusinessException.RESET_PWD_ACCOUNT_NOT_EXIST;
		}
		
		
		Account account = WeatherUtil.getAccountByEmail(email);

		if (account == null) {
			throw BusinessException.RESET_PWD_ACCOUNT_NOT_EXIST;
		}
        if (SecurityUtil.encryptoMD5String(loginPass).equals(account.getPayPassword())) {
        	request.setAttribute("message","pay.login.password.error");
			return mapping.findForward("failure");
		}
		String resetCode = IAccountConst.RESET_PWD_TYPE_LOGIN + ",e,"
				+ resetForm.getResetCode();
		if (account.getResetPwdCode() == null
				|| !account.getResetPwdCode().equals(resetCode)) {
			throw BusinessException.RESET_CODE_ERR_OR_INVALID;
		}

		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");
		service.resetLoginPassword(account.getId().longValue(), loginPass);

		return mapping.findForward("success");
	}

	/**
	 * 个人通过手机重置登录密码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward resetLoginPasswordByMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String mobile = resetForm.getMobile();
		HttpSession session = request.getSession();
		String mcrypt_key_1 = (String) session.getAttribute("mcrypt_key");// 获取session中随机因子
		session.removeAttribute("mcrypt_key");// 清除session
		String password1 = resetForm.getNewPass();
		String loginPass = AESWithJCE.getResult(mcrypt_key_1, password1);
		Account account = WeatherUtil.getAccountByMobile(mobile);

		if (account == null) {
			throw BusinessException.RESET_PWD_ACCOUNT_NOT_EXIST;
		}
		if (SecurityUtil.encryptoMD5String(loginPass).equals(account.getPayPassword())) {
	        	request.setAttribute("message","pay.login.password.error");
				return mapping.findForward("failure");
		}
		String resetCode = IAccountConst.RESET_PWD_TYPE_LOGIN + ",m,"
				+ resetForm.getResetCode();
		if (account.getResetPwdCode() == null
				|| !account.getResetPwdCode().equals(resetCode)) {
			throw BusinessException.RESET_CODE_ERR_OR_INVALID;
		}

		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");
		service.resetLoginPassword(account.getId().longValue(), loginPass);

		return mapping.findForward("success");
	}

	/**
	 * 填写激活码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward activate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IPBException, Exception {
		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");
		EmailForm theForm = (EmailForm) form;
		String email = theForm.getSys_email();
		String activeCode = theForm.getSys_activeCode();

		// 用户点击激活信里的链接直接激活
		if (StringUtil.isStrEmpty(email)) {
			email = request.getParameter("email");
			activeCode = request.getParameter("activeCode");
		}

		String scores = service.userActivate(email, activeCode);

		if (service.accountType(email) && StringUtils.isNotEmpty(scores)) {
			request.getSession().setAttribute("scores", scores);
			request.getSession().setAttribute(MESSAGE, ACTIVATE_SCORES);
		} else {
			request.getSession().setAttribute(MESSAGE, ACTIVATE_SUCCESS);
		}

		return mapping.findForward(SUCCESS);
	}

	/**
	 * 发送激活信
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward actimail(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		IAccountService service = (IAccountService) IPBAppFactory
				.getObj("accountService");
		EmailForm theForm = (EmailForm) form;
		SysSet setService = (SysSet) IPBAppFactory.getObj("sysSet");
		if (setService.getCheckVericode()) {
			String vericode = theForm.getSys_sys_vericode();
			this.checkVericode(request, vericode);
		}
		String email = theForm.getSys_email();
		String project = theForm.getSys_project();
		String url = ConvertUtil.getRequestURL(request);
		service.sendActivateMail(url, email, project);
		request.getSession().setAttribute(MESSAGE, ACTIMAIL_SUCCESS);
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		ServiceFacade sf = (ServiceFacade) IPBAppFactory
				.getObj("serviceFacade");
		Account ac = sf.getAccountDAO().getAccountById(new Long(accountId));
		if (ac != null) {
			request.setAttribute("email", email);
			return mapping.findForward("loginsuccess");
		}
		return mapping.findForward(SUCCESS);
	}

	public ActionForward reToRegister(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		RegisterForm theForm = (RegisterForm) form;
		String type = theForm.getRegister_atype();
		if (type.equals(Constant.ACCOUNT_TYPE_BUYER)) {
			return mapping.findForward("person");
		} else {
			return mapping.findForward("company");
		}
	}
	public ActionForward toForgot(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String email = resetForm.getEmail();
		if (StringUtils.isNotBlank(email)) {
			String regEx = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
			Pattern pat = Pattern.compile(regEx);
			Matcher mat = pat.matcher(email);
			boolean rs = mat.find();
			if (!rs) {
				throw BusinessException.RESET_PWD_ACCOUNT_NOT_EXIST;
			}
		}
		return mapping.findForward("success");
	}
	public ActionForward toResetLoginPasswordByEmail(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ResetPwdForm resetForm = (ResetPwdForm) form;
		String email = resetForm.getEmail();
		if (StringUtils.isNotBlank(email)) {
			String regEx = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
			Pattern pat = Pattern.compile(regEx);
			Matcher mat = pat.matcher(email);
			boolean rs = mat.find();
			if (!rs) {
				throw BusinessException.RESET_PWD_ACCOUNT_NOT_EXIST;
			}
		}
		return mapping.findForward("success");
	}


}
